package com.lancoo.dictionary.widget.globaltoast;

import java.util.Date;
import java.util.List;

import org.xutils.DbManager;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.ex.DbException;

import com.google.gson.Gson;
import com.lancoo.dictionary.DictionaryHelper;
import com.lancoo.dictionary.R;
import com.lancoo.dictionary.activity.DictionaryActicity;
import com.lancoo.dictionary.data.model.DicSearchBehavior;
import com.lancoo.dictionary.data.model.Meaning;
import com.lancoo.dictionary.data.model.Paraphrase;
import com.lancoo.dictionary.data.model.SearchHistory;
import com.lancoo.dictionary.data.model.Vocabulary;
import com.lancoo.dictionary.nc.NetworkConnection;

import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

final class GlobalToastController
		implements View.OnClickListener, View.OnTouchListener, ViewContainer.KeyEventHandler, CommonCallback<String> {

	private WindowManager mWindowManager;
	private Context mContext;
	private ViewContainer mWholeView;
	private View mContentView;
	private ViewDismissHandler mViewDismissHandler;
	private CharSequence mContent;
	private TextView mTextView;
	private TextView mMeaningView;
	private DbManager dbManager;

	public GlobalToastController(Context application, CharSequence content) {
		mContext = application;
		mContent = content;
		mWindowManager = (WindowManager) application.getSystemService(Context.WINDOW_SERVICE);
	}

	public void setViewDismissHandler(ViewDismissHandler viewDismissHandler) {
		mViewDismissHandler = viewDismissHandler;
	}

	public void updateContent(CharSequence content) {
		mContent = content;
		mTextView.setText(mContent);
	}

	public void show() {

		ViewContainer view = (ViewContainer) View.inflate(mContext, R.layout.lcdic_dic_pop_view, null);

		dbManager = DictionaryHelper.getDbManager();
		mMeaningView = (TextView) view.findViewById(R.id.dic_pop_chinese_meaning);
		String knowlegde = mContent.toString();
		try {
			SearchHistory searchHistory = dbManager==null?null:dbManager.findById(SearchHistory.class, knowlegde);
			if (searchHistory != null) {
				Vocabulary vocabulary = new Gson().fromJson(searchHistory.getMeaning(), Vocabulary.class);
				setChineseMeaning(vocabulary);
				DictionaryHelper.sendDicSearchBroadcast(mContext,vocabulary.getCwName(), DicSearchBehavior.SOURCE_DB,true);
			} else {
				new NetworkConnection(mContent.toString(), this);
			}
		} catch (DbException e) {
			e.printStackTrace();
		}

		// display content
		mTextView = (TextView) view.findViewById(R.id.dic_pop_search_str);
		mTextView.setText(mContent);

		mWholeView = view;
		mContentView = view.findViewById(R.id.dic_pop_content_view);

		// event listeners
		mContentView.setOnClickListener(this);
		mMeaningView.setOnClickListener(this);
		mWholeView.setOnTouchListener(this);
		mWholeView.setKeyEventHandler(this);

		int w = WindowManager.LayoutParams.MATCH_PARENT;
		int h = WindowManager.LayoutParams.MATCH_PARENT;

		int flags = 0;
		int type = 0;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			type = WindowManager.LayoutParams.TYPE_TOAST;
		} else {
			type = WindowManager.LayoutParams.TYPE_PHONE;
		}

		WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(w, h, type, flags,
				PixelFormat.TRANSLUCENT);
		layoutParams.gravity = Gravity.TOP;

		mWindowManager.addView(mWholeView, layoutParams);
	}

	@Override
	public void onClick(View v) {
		removePoppedViewAndClear();
		DictionaryActicity.startWithContent(mContext, mContent.toString());
	}

	private void removePoppedViewAndClear() {

		// remove view
		if (mWindowManager != null && mWholeView != null) {
			mWindowManager.removeView(mWholeView);
		}

		if (mViewDismissHandler != null) {
			mViewDismissHandler.onViewDismiss();
		}

		// remove listeners
		mContentView.setOnClickListener(null);
		mMeaningView.setOnClickListener(null);
		mWholeView.setOnTouchListener(null);
		mWholeView.setKeyEventHandler(null);
	}

	/**
	 * touch the outside of the content view, remove the popped view
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();
		Rect rect = new Rect();
		mContentView.getGlobalVisibleRect(rect);
		if (!rect.contains(x, y)) {
			removePoppedViewAndClear();
		}
		return false;
	}

	@Override
	public void onKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
			removePoppedViewAndClear();
		}
	}

	public interface ViewDismissHandler {
		void onViewDismiss();
	}

	/**
	 * networkConnection callback region
	 */
	@Override
	public void onSuccess(String result) {
		Vocabulary vocabulary = new Gson().fromJson(result, Vocabulary.class);
		if (vocabulary == null) {
			mMeaningView.setText(R.string.lcdic_search_failed);
			DictionaryHelper.sendDicSearchBroadcast(mContext,mContent.toString(), DicSearchBehavior.SOURCE_HTTP,false);
		} else {
			try {
				if (dbManager!=null){
					dbManager.saveOrUpdate(new SearchHistory(vocabulary.getCwName(), new Date(), result));
				}
			} catch (DbException e) {
				e.printStackTrace();
			}finally {
				DictionaryHelper.sendDicSearchBroadcast(mContext,mContent.toString(), DicSearchBehavior.SOURCE_HTTP,true);
			}
			setChineseMeaning(vocabulary);
		}

	}

	@Override
	public void onError(Throwable ex, boolean isOnCallback) {
		mMeaningView.setText(R.string.lcdic_search_failed);
		DictionaryHelper.sendDicSearchBroadcast(mContext,mContent.toString(), DicSearchBehavior.SOURCE_HTTP,false);
	}

	@Override
	public void onCancelled(CancelledException cex) {
	}

	@Override
	public void onFinished() {
	}

	/**
	 * networkConnection callback region
	 */

	private void setChineseMeaning(Vocabulary vocabulary) {
		StringBuilder cBuilder = new StringBuilder();
		List<Paraphrase> paraphrases = vocabulary.getCxCollection();
		for (int i = 0; i < paraphrases.size(); i++) {
			Paraphrase paraphrase = paraphrases.get(i);
			String cp = paraphrase.getCxChinese();
			if (!TextUtils.isEmpty(cp)) {
				cBuilder.append(cp).append('。');
			}
			List<Meaning> meanings = paraphrase.getMeanCollection();
			if (meanings == null) {
				continue;
			}
			for (int j = 0; j < meanings.size(); j++) {
				Meaning meaning = meanings.get(j);
				cBuilder.append(Html.fromHtml(meaning.getChineseMeaning()));
				if (j < meanings.size() - 1) {
					cBuilder.append('；');
				}
			}
			if (i < paraphrases.size() - 1) {
				cBuilder.append('\n');
			}
		}
		mMeaningView.setText(cBuilder);
	}
}
